﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using System.Text;

namespace V5_Common
{
    /// <summary>
    /// Velocity模板引擎
    /// </summary>
    public class VelocityHelper
    {
        private static readonly VelocityHelper m_Instance = new VelocityHelper();

        private string basePath = AppDomain.CurrentDomain.BaseDirectory;
        private string err = string.Empty;
        /// <summary>
        /// 
        /// </summary>
        public static VelocityHelper Instance
        {
            get { return m_Instance; }
        }
        /// <summary>
        /// 
        /// </summary>
        public VelocityHelper()
        {

        }
        private VelocityEngine velocity = null;
        private IContext context = null;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="templatDir">模板目录 根目录开始</param>
        public VelocityHelper(string templatDir)
        {
            Init(templatDir);
        }
        /// <summary>
        /// 初始话NVelocity模块
        /// </summary>
        /// <param name="templatDir"></param>
        private void Init(string templatDir)
        {
            //创建VelocityEngine实例对象
            velocity = new VelocityEngine();

            //使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();

            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
                HttpContext.Current.Server.MapPath(templatDir));
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
            #region 缓存设置
            //模板的缓存设置
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true);      //是否缓存
            props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)30);    //缓存时间(秒)
            #endregion
            velocity.Init(props);
            //为模板变量赋值
            context = new VelocityContext();
        }
        /// <summary>
        /// 给模板变量赋值
        /// </summary>
        /// <param name="key">标签</param>
        /// <param name="value">值 可以是值 也可以是类的对象</param>
        public void Put(string key, object value)
        {
            if (context == null)
                context = new VelocityContext();
            context.Put(key, value);
        }
        /// <summary>
        /// 输出模板
        /// </summary>
        /// <param name="templatFileName"></param>
        /// <returns></returns>
        public string Display(string templatFileName)
        {
            //从文件中读取模板
            Template template = velocity.GetTemplate(templatFileName);
            //合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);
            return writer.ToString();
        }

        public void DisplayResponse(string templatFileName) {
            //从文件中读取模板
            Template template = velocity.GetTemplate(templatFileName);
            //合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);
            //输出
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(writer.ToString());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// 生成静态文件
        /// </summary>
        /// <param name="templatFileName">模板名称</param>
        /// <param name="outFile">生成文件地址</param>
        public void Display(string templatFileName, string outFile)
        {
            FsoHelper fso = new FsoHelper();
            fso.CreateFile(outFile, Display(templatFileName));
        }

        /// <summary>
        /// 获取字符串格式化内容
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public void InitTemplateByString(string strContent)
        {
            //if (File.Exists(basePath + "/tempVelocityTemplate.html"))
            //    File.Delete(basePath + "/tempVelocityTemplate.html");
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(basePath + "/tempVelocityTemplate.html", false, Encoding.UTF8);
                sw.Write(strContent);
                sw.Flush();
                Init("");
            }
            catch (Exception ex)
            {
                err = ex.Message;
            }
            finally
            {
                sw.Close();
            }
        }
        /// <summary>
        /// 输入字符串格式化后的模板 配合InitTemplateByString使用
        /// </summary>
        /// <returns></returns>
        public string DisplayTemplateByString()
        {
            if (string.IsNullOrEmpty(err))
            {
                return Display("tempVelocityTemplate.html");
            }
            return err;
        }
    }
}
